<?php


namespace app\api\controller;
//脱硫实时
use app\common\service\CommonService;
use app\common\service\companyIndustry\industrymodel\TsinghuaDrainEmissionToFacilityParam;
use app\common\service\companyIndustry\realtime\SulfurCaSRatioService as RealSo2Ca;
use app\common\service\companyIndustry\realtime\SulfurConcentrationService as RealSo2Con;
use app\common\service\companyIndustry\realtime\SulfurEfficiencyService as RealSo2Effi;
use app\common\service\companyIndustry\realtime\SulfurLiquidGasRatioService as RealSo2Liquid;
use app\common\service\companyIndustry\realtime\SulfurPumpService as RealSo2Pump;
use app\common\service\companyIndustry\realtime\SulfurSlurrySupplyService as RealSo2Slurry;
//脱硫方案
use app\common\service\companyIndustry\tsinghua\SulfurCaSRatioService as TsinghuaSo2Ca;
use app\common\service\companyIndustry\tsinghua\SulfurConcentrationService as TsinghuaSo2Con;
use app\common\service\companyIndustry\tsinghua\SulfurEfficiencyService as TsinghuaSo2Effi;
use app\common\service\companyIndustry\tsinghua\SulfurLiquidGasRatioService as TsinghuaSo2Liquid;
use app\common\service\companyIndustry\tsinghua\SulfurPumpService as TsinghuaSo2Pump;
use app\common\service\companyIndustry\tsinghua\SulfurSlurrySupplyService as TsinghuaSo2Slurry;
//脱硝实时
use app\common\service\companyIndustry\realtime\NitreConcentrationService as RealNo2Con;
use app\common\service\companyIndustry\realtime\NitreEfficiencyService as RealNo2Effi;
//脱硫方案
use app\common\service\companyIndustry\tsinghua\NitreConcentrationService as TsinghuaNo2Con;
use app\common\service\companyIndustry\tsinghua\NitreEfficiencyService as TsinghuaNo2Effi;
//其他
use app\common\service\companyIndustry\tsinghua\TsinghuaEmissionService;
use app\common\service\CompanyService;
use app\common\service\ControlEmissionService;
use app\common\service\ControlService;
use app\common\service\EmissionService;
use app\common\service\FormulaService;
use app\common\service\InletFlueGasService;
use app\common\service\WorkingModelService;
use think\Db;
use think\Exception;
use think\Request;
use app\common\service\CompanyIndustryService;

class Control extends BaseController
{
    public static $companyList = [];
    public static $stationList = [];
    public static $param = [];
    public static $standardEmission = [];
    public $drainList = [];

    public function __construct(Request $request)
    {
        parent::__construct($request);
        static::$companyList      = db('basic_company')->field(['id', 'name', 'short_name', 'industry_id'])->where('delete_time', 'eq', 0)->select();
        static::$companyList      = array_combine(array_column(static::$companyList, 'id'), array_values(static::$companyList));
        static::$standardEmission = db('basic_emission_standards')->field(['id', 'industry_id', 'emission_so2', 'emission_nox'])->whereIn('id', [1, 2, 10, 11])->select();
        static::$standardEmission = array_combine(array_column(static::$standardEmission, 'industry_id'), array_values(static::$standardEmission));

        $drain = db('basic_drain')->where('delete_time', 'eq', 0)->select();
        foreach ($drain as $k => $v) {
            $this->drainList[$v['company_id']][$v['name']] = $v;
        }

        static::$stationList = [
            1 => '长治八中',
            2 => '德盛苑',
            3 => '监测站',
            4 => '清华站',
            5 => '审计局'
        ];
    }

    /**
     * 获取已完成预案列表
     * @author hongwei 2019-06-24
     */
    public function getControlPlanList()
    {
        $sql  = 'select a.*,b.name as plane_type_name from control_plan_name as a left join control_plan_type as b on a.plan_type = b.id and a.control_end_time< now() order by a.id desc';
        $data = Db::query($sql);
        if (!$data) {
            throw new \Exception('获取已完成预案列表失败！');
        }
        $this->success('获取已完成预案列表成功', $data);
    }

    /**
     * 获取初始化今天的预案名称
     * @throws \Exception
     * @author hongwei 2019-06-24
     */
    public function initControlPlanName()
    {
        $sql  = 'select * from control_plan_name order by id desc limit 0,1';
        $data = Db::query($sql);
        if (!$data) {
            throw new \Exception('获取初始化今天的预案名称失败！');
        }
        $this->success('获取初始化今天的预案名称成功', $data[0]);
    }


    /**
     * 第一步 - 管控清单获取
     * @throws \MongoDB\Driver\Exception\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author  dutongtong   2019/7/12
     * @author  dutongtong   2019/7/15
     */
    public function controlList()
    {
        $planNumber = $this->request->param('plan_number');

        $validate = V([
            'plan_number' => 'require'
        ]);
        if (isset($validate['msg'])) {
            $this->error($validate['msg']);
        }

        $data          = db::name('control_setting_list')
            ->field('type,company_id,plan_number,operating_efficiency as efficiency,control_status,emission as emissions,drain_name as outlet,contribution_degree as contribution,operation_concentration as concentration,station_id')
            ->where(['plan_number' => $planNumber])
            ->select();
        $commonService = new CommonService();
        foreach ($data as $key => $val) {
            $val['station_name'] = self::$stationList[$val['station_id']];
            $val['entriprise']   = self::$companyList[$val['company_id']]['short_name'];
            // $val['concentration'] .= 'mg/m³';
            $val['emissions']    = round($val['emissions'], 2);
            $val['contribution'] = $commonService->contributionRound($val['contribution']);
            $val['efficiency']   *= 100;

            $c[$val['type'] == 'PM2.5' ? 'PM2_5' : $val['type']][] = $val;
        }
        $this->success('获取管控清单成功', $c);
    }

    /**
     * 第一步 - 管控目标制定
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author ayy 2019/07/16
     */
    public function controlIndustryList()
    {
        $data = V([
            'plan_number'   => 'require',//预案编号
            'industry_type' => 'require|number|in:1,2'//行业类型
        ]);
        if (isset($data['msg'])) {
            $this->error($data['msg']);
        }

        $data = Db::name('control_setting_list')
            ->alias('sl')
            ->leftJoin('basic_company c', 'c.id = sl.company_id')
            ->where(['sl.plan_number' => $data['plan_number'], 'sl.industry_type' => $data['industry_type'], 'sl.region_id' => 53, 'type' => ['SO2', 'NO2']])
            ->field('sl.drain_name,c.short_name company_name,sl.emission,sl.type')
            ->select();
        $list = [
            'SO2' => [],
            'NO2' => []
        ];
        foreach ($data as $val) {
            $val['emission'] = round($val['emission'], 2);
            if ($val['type'] == 'SO2') {
                $list['SO2'][] = $val;
            } elseif ($val['type'] == 'NO2') {
                $list['NO2'][] = $val;
            }
        }
        $this->success('管控目标制定列表获取成功', $list);
    }

    /**
     * 第一步：修改预案名称
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @auther ayy 2019/07/16
     */
    public function changePlanName()
    {
        $param      = $this->request->param();
        $planName   = $param['plan_name'];
        $planNumber = $param['plan_number'];
        $res        = Db::name('control_plan_name')
            ->where(['plan_number' => $planNumber])
            ->update(['plan_name' => $planName]);
        if ($res === false) {
            $this->error('预案名称修改失败');
        }
        $this->success('预案名称修改成功');
    }

    /**
     * 调入清华预案方案
     * @author hongwei 2019-06-26
     */
    public function getTsinghuaPlanName()
    {
        $planName = $this->request->param('plan_number');
        $sql      = 'select * from control_plan_from_tsinghua_plan where plan_number = "' . $planName . '" order by id asc';
        $data     = Db::query($sql);
        if (!$data) {
            $this->error('调入清华预案方案失败！');
        }
        $this->success('调入清华预案方案成功', $data);
    }

    /**
     * 获取管控措施名称
     * @author hongwei 2019-06-27
     */
    public function getBasicControlMeasure()
    {
        $sql  = "select * from basic_control_measure order by id asc";
        $data = Db::query($sql);
        if (!$data) {
            $this->error('获取管控措施名称失败!');
        }
        $this->success('获取管控措施名称成功！', $data);
    }

    /**
     * 获取管控方式
     * @author hongwei 2019-06-27
     */
    public function getBasicControlMode()
    {
        $sql  = "select * from basic_control_mode order by id asc";
        $data = Db::query($sql);
        if (!$data) {
            $this->error('获取管控方式失败！');
        }
        $this->success('获取管控方式成功！', $data);
    }

    /**
     * 管控下达人员
     * @author hongwei 2019-06-27
     */
    public function toEpa()
    {
        $param            = $this->request->param();
        $controlModeId    = $param['control_mode_id']; //管控方式ID
        $controlMeasureId = isset($param['control_measure_id']) ? $param['control_measure_id'] : 0; //管控措施ID，默认是全部

        $sql = 'select a.*,
b.name as company_name,
c.name as control_measure_name,
d.name as control_mode_name,
e.username as epa_receive_username,e.mobile as epa_receive_mobile,
f.username as epa_charge_username,f.mobile as epa_charge_mobile 
from control_to_epa as a 
left join basic_company as b on a.company_id = b.id  
left join basic_control_measure as c on a.control_measure_id = c.id 
left join basic_control_mode as d on a.control_mode_id = d.id 
left join basic_epa_people e on a.receive_user_id = e.id
left join basic_epa_people f on a.charge_user_id = f.id where ';
        if ((int)$controlMeasureId == 0) {
            $sql .= 'a.control_measure_id in (1,2,3)';  //全部
        } else {
            $sql .= 'a.control_measure_id=' . $controlMeasureId; //传指定ID
        }
        $sql  .= ' and a.control_mode_id = ' . $controlModeId;
        $data = Db::query($sql);

        //返回
        if (empty($data)) {
            $this->error('获取管控下达人员列表为空！', []);
        }
        if (!$data) {
            $this->error('获取管控下达人员列表失败！');
        }
        $this->success('获取管控下达人员列表成功！', $data);
    }

    /**
     * 6-获取公司管控跟踪的企业信息
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-10
     */
    public function controlSixCompany()
    {
        //step1:传参
        $param         = $this->request->param();
        $controlModeId = isset($param['control_mode_id']) ? $param['control_mode_id'] : 1;  //类型,默认为工业减排
        $type          = isset($param['type']) ? strtoupper($param['type']) : 'SO2';  //类型
        $planNumber    = $param['plan_number'];  //预案编号

        //step2:查看预案是否确认过
        $control     = new ControlService();
        $confirmPlan = $control->existConfirmTsinghuaPlanByPlanNumber($planNumber); //是否有确认的清华预案
        if (!$confirmPlan) {
            $this->error('此方案还没有确认，待确认后才能进行查看与操作！');
        }

        //step4:获取企业的减排前和方案值的排放量（主要获取目标排放量）
        $emission         = new EmissionService();
        $tsinghuaPlanName = $control->getConfirmTsinghuaPlanByPlanNumber($planNumber); //清华预案名称
        $controlEmission  = new ControlEmissionService();
        $lastEmission     = $controlEmission->getTsinghuaCompanyEmission($type, $controlModeId, $planNumber, $tsinghuaPlanName, 'kg');

        //step5:获取已完成减排量开始计算条件
        $control          = new ControlService();
        $completeDays     = $control->getPlanNumberDays($planNumber);
        $completeStartDay = $control->getPlanNumberStartDay($planNumber);
        $completeEndDay   = $control->getPlanNumberEndDay($planNumber);
        if (strtotime($completeStartDay) >= time()) {
            $this->error('管控时段还未开始，不能进行统计！');
        }

        //step6:获取已完成减排量开始计算
        foreach ($lastEmission as $k => $v) {
            $drainEmission = $emission->getSingleCompanyDrainEmissionMinToHourAvg((int)$v['company_id'], $completeEndDay, $completeDays, 'kg');
            foreach ($drainEmission as $k2 => $v2) {
                if ((int)$v['drain_id'] == (int)$v2['drain_id']) {
                    if ($type == 'NOX') {
                        $lastEmission[$k]['complete_emission'] = (int)$v2['company_id'] == 1 ? $v2['nox_emissions_supplement'] : $v2['nox_emissions']; //已完成减排量
                    }
                    if ($type == 'SO2') {
                        $lastEmission[$k]['complete_emission'] = (int)$v2['company_id'] == 1 ? $v2['so2_emissions_supplement'] : $v2['so2_emissions']; //已完成减排量
                    }
                    $formula                                                   = new FormulaService();
                    $lastEmission[$k]['completion_rate_of_emission_reduction'] = $formula->completionRateOfEmissionReduction($lastEmission[$k]['complete_emission'], $lastEmission[$k]['target_emissions']);
                }
            }

            //运行浓度，todo 待制作
            $lastEmission[$k]['operating_concentration_before']   = 0; //减排前运行浓度
            $lastEmission[$k]['operating_concentration_tsinghua'] = 0; //方案值运行浓度
            $lastEmission[$k]['operating_concentration_average']  = 0; //当前值平均值运行浓度

            //运行效率，todo 待制作
            $lastEmission[$k]['operating_efficiency_before']   = 0; //减排前运行效率
            $lastEmission[$k]['operating_efficiency_tsinghua'] = 0; //方案值运行效率
            $lastEmission[$k]['operating_efficiency_average']  = 0; //当前值平均值运行效率

            //删除不必要的字段
            unset($lastEmission[$k]['origin_emissions']); //去掉原始减排量
            unset($lastEmission[$k]['tsinghua_emissions']); //去掉方案减排量
        }


        //返回
        if (!$lastEmission) {
            $this->error('获取公司管控跟踪的企业信息 失败！');
        }
        $this->success('获取公司管控跟踪的企业信息 成功', $lastEmission);
    }

    /**
     * 2-2-根据排放量获取设施参数
     * @author hongwei 2019-07-10
     */
    public function getFacilityParamByEmission()
    {
        $url  = "http://39.96.33.44:8081/renren-api/jnrdgk/disassemble?mOutHour=2&qin=11&qin=22&rouIn=33&rouIn=44&qOut=55&qOut=66&m=2";
        $data = curl_request($url);
        if ($data['code'] == 1) {
            $this->error('根据排放量获取设施参数 失败!');
        }
        $newData['yita']   = $data['yita'];
        $newData['rouOut'] = $data['rouOut'];
        $this->success('根据排放量获取设施参数 成功!', $newData);
    }

    /**
     * 管控第2步右侧：根据传企业ID得到设施
     * @author hongwei 2019-07-18
     */
    public function getFacilityByCompanyId()
    {
        $param     = $this->request->param();
        $companyId = $param['company_id']; //公司ID
        $type      = isset($param['type']) ? $param['type'] : 'SO2';       //污染物类型,默认是SO2
        $company   = new CompanyService();
        $result    = [];
        try {
            $result = $company->getFacilityByCompanyIdAndType($companyId, $type, 'id,name,name_cn,company_id');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('获取信息成功！', $result);
    }


    /**
     * 获取预测模型的供浆量和循环泵开关组合
     * @param $param
     * @param $cis
     * @param $wms
     * @return array
     */
    public function callForecast($param, $cis, $wms)
    {
        $times    = $this->getControlTime($param['plan_number']);#查询获取管控时间
        $facility = $this->facilityConversion($param['facility_id']);#查询获取设施信息
        $result   = [];

        if ($facility['type'] == "TS") {
            $gasInVol   = $cis->getGasInVol($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $gasOutVol  = $cis->getGasOutVol($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $so2InDen   = $cis->getSO2InDen($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $so2OutDen  = $cis->getSO2OutDen($param['plan_number'], $param['tsinghua_plan_name'], $param['facility_id']);
            $o2InPer    = $cis->getO2InPer($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $o2OutPer   = $cis->getO2OutPer($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $gasInTemp  = $cis->getGasInTemp($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $gasOutTemp = $cis->getGasOutTemp($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);
            $caQual     = $cis->getCaQual();
            $caDen      = $cis->getCaDen($param['company_id'], $facility['machine'], $facility['facility'], $times['startTime'], $times['endTime'], $facility['type']);

            switch ($facility['machine']) {
                case 1:
                    $result = $wms->tsForecast1($gasInVol, $gasOutVol, $so2InDen, $so2OutDen, $o2InPer, $o2OutPer, $gasInTemp, $gasOutTemp, $caQual, $caDen);
                    break;
                case 2:
                    $result = $wms->tsForecast1($gasInVol, $gasOutVol, $so2InDen, $so2OutDen, $o2InPer, $o2OutPer, $gasInTemp, $gasOutTemp, $caQual, $caDen);
                    break;
            }
        }

        $result = json_decode($result, true);

        return ['pumpGroup' => $result['pumpGroup'], 'slurrySupply' => $result['slurrySupply']];
    }


    /**
     * 通过设施ID获取信息
     * @param $facilityId
     * @return array
     */
    private function facilityConversion($facilityId): array
    {
        $sql      = "SELECT `name` FROM `basic_facility` WHERE id = ?";
        $facility = Db::query($sql, array($facilityId));
        if (empty($facility)) {
            $this->error('未知设施');
        }
        $facilityName = $facility[0]['name'];

        $arr            = explode('-', $facilityName);
        $str            = substr($arr[1], strlen($arr[1]) - 1, 1);
        $facilityNumber = is_numeric($str) ? chr($str + 96) : false;

        $result = [
            'machine'  => substr($arr[1], 0, 1),
            'facility' => $facilityNumber,
            'type'     => $arr[0],
        ];
        return $result;
    }
}